#!/bin/sh
. /usr/share/libubox/jshn.sh
. /lib/functions.sh

HOSTSFILE="-1"

find_hosts_config() {
	local cfg="$1"

	config_get library "$cfg" library
	if [ "$library" != "olsrd_nameservice" ]; then
		return 1
	fi
	config_get hosts_file "$cfg" hosts_file
	HOSTSFILE=$hosts_file
}

load_hosts() {
	config_load olsrd
	config_foreach find_hosts_config LoadPlugin
	local hosts4=$(cat $HOSTSFILE)
	HOSTSFILE=""
	config_load olsrd6
	config_foreach find_hosts_config LoadPlugin
	if [ -f "$HOSTSFILE" ]; then
		local hosts6=$(cat "$HOSTSFILE")
	else
		local hosts6=""
	fi
	local hosts="$hosts4$hosts6"
	json_init
	json_add_string hosts "$hosts"
	json_dump
}

case "$1" in
list)
	json_init
	json_add_object "getjsondata"
	json_add_string 'otable' 'String'
	json_add_int 'v4_port' 'Integer'
	json_add_int 'v6_port' 'Integer'
	json_close_object
	json_add_object "hasipip"
	json_close_object
	json_add_object "hosts"
	json_close_object
	json_dump
	;;
call)
	case "$2" in
	getjsondata)
		json_init
		json_load "$(cat)"
		json_get_var otable otable
		json_get_var v4_port v4_port
		json_get_var v6_port v6_port

		jsonreq4=$(echo "/${otable}" | nc 127.0.0.1 "${v4_port}" | sed -n '/^[}{ ]/p' 2>/dev/null)
		jsonreq6=$(echo "/${otable}" | nc ::1 "${v6_port}" | sed -n '/^[}{ ]/p' 2>/dev/null)

		json_init
		json_add_string "jsonreq4" "$jsonreq4"
		json_add_string "jsonreq6" "$jsonreq6"
		json_dump
		;;
	hasipip)
		result=$(ls /etc/modules.d/ | grep -E "[0-9]*-ipip")
		json_init
		json_add_string "result" "$result"
		json_dump
		;;
	hosts)
		load_hosts
		;;
	esac
	;;
esac
